﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Easy.BLL;
using Easy.Model;
using Easy.Operation;
using Easy.Common;

namespace Easy.Web.Service.Setting
{
    /// <summary>
    /// SetUserImg 的摘要说明
    /// </summary>
    public class SetUserImg : BaseHttpHandler
    {

        public override void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string msg = "";
            try
            {
                HttpPostedFile file = context.Request.Files[0];
                if (file != null)
                {
                    string filename = Path.GetFileName(file.FileName);
                    string Extension = Path.GetExtension(filename).ToLower();
                    //gif、jpg、jpeg、png，
                    if (Extension == ".gif" || Extension == ".jpg" || Extension == ".jpeg" || Extension == ".png")
                    {
                        int filelength = file.ContentLength;
                        if (filelength <= 300 * 1024)
                        {
                            //uploadfiles/userimg/用户工号.扩展名，同名则覆盖context.User.Identity.Name
                            string path = "uploadfiles/userimg/" + context.User.Identity.Name + Extension;
                            DataService service = new DataService("systemuser",new Guid(Config.AdminUserId));
                            Dictionary<string, object> user = new Dictionary<string, object>();
                            user.Add("systemuserid", CurrentUserId);
                            user.Add("userimg", "/"+ path);
                            service.Update(user);
                            file.SaveAs(HttpContext.Current.Server.MapPath("/") + path);
                            msg = "{\"Result\":\"/" + path + "\"}";

                        }
                        else
                        {
                            msg = "{\"ErrorCode\":\"错误代码待定\",\"ErrorMessage\":\"图片过大\"}";
                        }
                    }
                    else
                    {
                        msg = "{\"ErrorCode\":\"错误代码待定\",\"ErrorMessage\":\"图片格式有误\"}";
                    }
                }
                else
                {
                    msg = "{\"ErrorCode\":\"错误代码待定\",\"ErrorMessage\":\"请选择文件\"}";
                }
            }
            catch(Exception ex)
            {
                msg = "{\"ErrorCode\":\"错误代码待定\",\"ErrorMessage\":\"" + ex.Message.Replace("\"", "").Replace("\\", "\\\\") + "\"}";
            }
            context.Response.Write(msg);
        }

    }
}